//
//  ViewController.m
//  AoJi
//
//  Created by 杨行 on 15/1/20.
//  Copyright (c) 2015年 xuanheng. All rights reserved.
//

#import "MainViewController.h"
#import "ICSDrawerController.h"
#import "SingleImageTableViewCell.h"
#import "DoubleImageTableViewCell.h"


#import "YHNetwork.h"
#import "NSObject+CommonClass.h"
#import "UIImageView+WebCache.h"
#import "DataSingleTon.h"
#import "EnglishLearnController.h"
#import "XHYWebViewController.h"
#import "AJMoreinfoViewController.h"
#import "guessYouLikerController.h"
#import "NationalStudyViewController.h"

#import "ForeignStudyViewController.h"
#import "LoginViewController.h"
#import "HomeLoopWebViewController.h"
@interface MainViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,CustomImageViewDelegate>
{
    
    UIButton *rightBtn;
    UIButton *leftBtn;
    UITableView *contentTableView;
    float itemHeight;
    
    NSMutableArray *loopArray;
    UIPageControl *pageControl;
    UILabel *titleLabel;
    int currentindex;
}
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    kLightContent;
    
    NSLog(@"nshomeder===%@",NSHomeDirectory());
    [self getCityList];
    [self getCountryList];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self setTopScrollview];
    [self getInfo];
    [self initContentView];
    
    [self hideNavigationBar];
    
//    [super viewDidLoad];
    
    
    leftBtn=[[UIButton alloc]initWithFrame:CGRectMake(-5,10, 50, 50)];
//    leftBtn=[[UIImageView alloc]initWithFrame:CGRectMake(0,10, 50, 50)];
//    leftBtn.image=[UIImage imageNamed:@"homeLeft.png"];
    leftBtn.contentMode=UIViewContentModeScaleAspectFill;

    [leftBtn setImage:[UIImage imageNamed:@"homeLeft.png"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(jumpToHomeViewVc) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftBtn];
    
    
    rightBtn=[[UIButton alloc]initWithFrame:CGRectMake(Mainwidth-45,10, 50, 50)];
    [rightBtn setImage:[UIImage imageNamed:@"gerengzhongx.png"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(jumpToPersonalViewVc) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:rightBtn];
    
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)viewWillAppear:(BOOL)animated
{
    
    kLightContent;

    if(self.loadtype==LoadTypeBack){
        
//        self.topScrollview.contentInset=UIEdgeInsetsMake(-20,0, 0, 0);
        NSLog(@"loadtype==LoadTypeBack");
    }


}

- (void)viewDidAppear:(BOOL)animated
{

    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)getInfo
{
    self.automaticallyAdjustsScrollViewInsets=NO;
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    [dic setObject:@(1) forKey:@"category"];
    NSLog(@"dic---->%@",dic);
    
    //标题的背景视图
    UIView * titleBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0,Mainwidth/2-30, Mainwidth, 30)];
    titleBackgroundView.backgroundColor = [UIColor blackColor];
    titleBackgroundView.alpha = 0.5;
    [self.view addSubview:titleBackgroundView];
    
    
    titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(3, Mainwidth/2-30, Mainwidth - 6, 30)];
    [self.view addSubview:titleLabel];
    titleLabel.textAlignment=NSTextAlignmentLeft;
    titleLabel.font=[UIFont systemFontOfSize:15];
    titleLabel.textColor=[UIColor whiteColor];
    
    

    
    [YHNetwork getInformationWithReguestType:RequestTypeGet WithParameters:dic WithApi:@"uploads" WhenSuccess:^(NSMutableDictionary *response) {
    
        loopArray=response;
        for (int i=0; i<loopArray.count; i++) {
            UIImageView *imgview=[[UIImageView alloc]initWithFrame:CGRectMake(Mainwidth*i, 0, Mainwidth, Mainwidth/2)];
            
            
            NSURL *url=[self getPicUrl:[loopArray[i] objectForKey:@"img_url"]];
            
            [imgview sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"ad.png"]];
            imgview.userInteractionEnabled=YES;
            UIGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapTheLoopImgview:)];
            
            imgview.tag=i;
            [imgview addGestureRecognizer:tap];
            [self.topScrollview addSubview:imgview];
            UIImage *topChange=[UIImage imageNamed:@"mainviewdingbujianbian.png"];
            
            UIView *topchangeImg=[[UIView alloc]initWithFrame:CGRectMake(Mainwidth*i, 0, Mainwidth,topChange.size.height)];
            topchangeImg.tag=i;
            topchangeImg.backgroundColor=[UIColor colorWithPatternImage:topChange];
            tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapTheLoopImgview:)];
            [topchangeImg addGestureRecognizer:tap];
            [self.topScrollview addSubview:topchangeImg];
            
            if (i==0) {
                titleLabel.text=[loopArray[i] objectForKey:@"title"];
            }
            
            NSLog(@"imageView.top------%f",imgview.frame.origin.y);
        }
        
        
        
        self.topScrollview.contentSize=CGSizeMake(Mainwidth*loopArray.count, 0);
       
        pageControl.numberOfPages=loopArray.count;
        
        
    } WhenFailure:^(NSError *failure) {
//        NSLog(@"error--->%@",failure);
    }];
 
    if (self.loadtype==loadFromSideMenu) {
        NSLog(@"loadtype==loadFromSideMenu");
        
    }else if(self.loadtype==loadNotFromSideMenu){
        
//        self.topScrollview.contentInset=UIEdgeInsetsMake(-20,0, 0, 0);
        
        NSLog(@"loadtype==loadNotFromSideMenu");
    }else if(self.loadtype==LoadTypeBack){
        
//        self.topScrollview.contentInset=UIEdgeInsetsMake(20,0, 0, 0);
        NSLog(@"loadtype==LoadTypeBack");
    }

}

-(void)setTopScrollview
{
    
    _topScrollview=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, Mainwidth, Mainwidth/2)];
    _topScrollview.pagingEnabled=YES;
    _topScrollview.delegate=self;
    _topScrollview.showsHorizontalScrollIndicator=NO;
    [self.view addSubview:_topScrollview];
    
    pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake(Mainwidth-80, Mainwidth/2-30, 80, 40)];
    [self.view addSubview:pageControl];
    
    pageControl.currentPage=0;
    pageControl.hidesForSinglePage=YES;
    
    //顶部title
    UILabel *topTitleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, viewTop(rightBtn)+25, Mainwidth, 20)];
    topTitleLabel.text=@"澳际教育";
    topTitleLabel.font=[UIFont systemFontOfSize:14];
    topTitleLabel.textColor=[UIColor whiteColor];
    topTitleLabel.textAlignment=NSTextAlignmentCenter;
    [self.view addSubview:topTitleLabel];

}


-(void)initContentView
{
   
    contentTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, Mainwidth/2, Mainwidth, MainHeight-Mainwidth/2-5)];
    [self.view addSubview:contentTableView];
    contentTableView.dataSource=self;
    contentTableView.delegate=self;
    contentTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    contentTableView.scrollEnabled=NO;
    
     itemHeight=viewHeight(contentTableView)/3.5;
    
    NSLog(@"contentTableView--->%f",contentTableView.frame.origin.y);
    
}


-(void)tapThecontenItem:(UIGestureRecognizer*)tap
{
    NSLog(@"tag==%i",[tap view].tag);
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    int Y=11/2;
    if (indexPath.row==0) {
        SingleImageTableViewCell *cell=[[SingleImageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        UIImage *image1=[UIImage imageNamed:@"chuguoliux.png"];
        
        cell.singleImageview.layer.contents=(id)image1.CGImage;
       
        cell.singleImageview.contentMode=UIViewContentModeScaleAspectFit;
        cell.singleImageview.frame=CGRectMake(7,Y, Mainwidth-14, itemHeight-Y);
        cell.singleImageview.backgroundColor=[self getBackGroundImg:@"chuguoliux.png"];
        cell.singleImageview.delegate=self;
        cell.singleImageview.tag=0;

        return cell;
    }
    
    else if (indexPath.row==1)
    {
        
        DoubleImageTableViewCell *cell=[[DoubleImageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
      
        UIImage *ima = [UIImage imageNamed:@"yingyupeix.png"];// 原图片 A
        CGRect rect = CGRectMake(5, 5, 5, 5);// 原图片A中需要显示的位置区域B
        
        CGImageRef imageRef = CGImageCreateWithImageInRect([ima CGImage], rect); //获得剪切区域B
        
        UIImage *subIma = [UIImage imageWithCGImage:imageRef]; // 把B转化成一张图片
        
        cell.firstImageview.contentMode=UIViewContentModeScaleAspectFit;
        cell.firstImageview.layer.contents=[self getCgimage:@"yingyupeix.png"];
        cell.firstImageview.backgroundColor=[UIColor colorWithPatternImage:subIma];
        cell.secondImageview.image=[UIImage imageNamed:@"chuguoliuxue.png"];
        cell.secondImageview.contentMode=UIViewContentModeScaleAspectFit;
        cell.secondImageview.backgroundColor=[self getBackGroundImg:@"chuguoliuxue.png"];
        cell.firstImageview.frame=CGRectMake(7,Y, Mainwidth/2-19/2, itemHeight-Y);
        cell.secondImageview.frame=CGRectMake(12+Mainwidth/2-19/2,Y, Mainwidth/2-19/2, itemHeight-Y);
        
        cell.firstImageview.delegate=self;
        cell.secondImageview.delegate=self;
        cell.firstImageview.tag=1;
        cell.secondImageview.tag=2;
        
        
        return cell;
        
        
    }else if (indexPath.row==2)
    {
        DoubleImageTableViewCell *cell=[[DoubleImageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.firstImageview.contentMode=UIViewContentModeScaleAspectFit;
        cell.secondImageview.contentMode=UIViewContentModeScaleAspectFit;
       
        
        
        cell.firstImageview.layer.contents=[self getCgimage:@"guojixuexiao.png"];
        cell.secondImageview.layer.contents=[self getCgimage:@"guanwang.png"];
        cell.firstImageview.frame=CGRectMake(7,Y, Mainwidth/2-19/2, itemHeight-Y);
        cell.secondImageview.frame=CGRectMake(12+Mainwidth/2-19/2,Y, Mainwidth/2-19/2, itemHeight-Y);
        
        
        cell.secondImageview.backgroundColor=[self getBackGroundImg:@"guanwang.png"];
        cell.firstImageview.backgroundColor=[self getBackGroundImg:@"guojixuexiao.png"];
        cell.firstImageview.delegate=self;
        cell.secondImageview.delegate=self;
        
        cell.firstImageview.tag=3;
        cell.secondImageview.tag=4;
        
        return cell;
        
        
    }
    else{
        
        
        
        SingleImageTableViewCell *cell=[[SingleImageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.singleImageview.contentMode=UIViewContentModeScaleAspectFit;
        [cell.singleImageview setImage:[UIImage imageNamed:@"cainixihuan.png"]];
        cell.singleImageview.frame=CGRectMake(7,Y, Mainwidth-13,itemHeight/2-Y);
        cell.singleImageview.backgroundColor=[self getBackGroundImg:@"cainixihuan.png"];
        cell.singleImageview.delegate=self;
        cell.singleImageview.tag=5;
        return cell;
        
    }
    
    
    
    
}
-(UIColor *)getBackGroundImg:(NSString*)imgName
{
    CGImageRef imgRf=CGImageCreateWithImageInRect([[UIImage imageNamed:imgName] CGImage], CGRectMake(5, 5, 5, 5));
    UIColor *color1=[UIColor colorWithPatternImage:[UIImage imageWithCGImage:imgRf]];
    return color1;

}

-(id)getCgimage:(NSString *)imgname
{

    UIImage *temImg=[UIImage imageNamed:imgname];
    return temImg.CGImage;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row==3) {
        return itemHeight/2;
    }else{
        
        return itemHeight;
    }
    
}
#pragma mark scrollviewdelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
   
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    currentindex=(int)floor(scrollView.contentOffset.x)/Mainwidth;
    NSLog(@"currentindex==%i",currentindex);
    
    titleLabel.text=[loopArray[currentindex] objectForKey:@"title"];
    pageControl.currentPage=currentindex;

}

#pragma mark 抽屉页
-(void)jumpToHomeViewVc
{
    
    [[NSNotificationCenter defaultCenter]postNotificationName:kSideMenuOpen object:@(0)];
    [self.drawer open];
    
}

-(void)jumpToPersonalViewVc
{
    //设置不能点击
    if (![kUserDefaults objectForKey:kAccessToken]) {
//        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"亲,您还没有登陆嘞!" delegate:self cancelButtonTitle:@"马上去登陆" otherButtonTitles:@"再看看吧", nil];
//        [alertView show];
        
        
        [self presentViewController:[[LoginViewController alloc]init] animated:NO completion:^{
            
        }];
    }else{
       
        
       
        [[NSNotificationCenter defaultCenter]postNotificationName:kTurnOffTheAnimition object:@(0)];
        [self.drawer open];

       
        [self performSelector:@selector(followingMethod) withObject:nil afterDelay:0.1];
        
        
        
    }

}

-(void)followingMethod
{
    PersonalViewController *personalVC = [[PersonalViewController alloc]init];
    [self.drawer replaceCenterViewControllerWithViewController:personalVC];
    
    


}

#pragma mark - ICSDrawerController

- (void)drawerControllerWillOpen:(ICSDrawerController *)drawerController
{
    self.view.userInteractionEnabled = NO;
}

- (void)drawerControllerWillClose:(ICSDrawerController *)drawerController
{
    self.view.userInteractionEnabled = YES;
}


-(void)tapTheLoopImgview:(UIGestureRecognizer*)tap
{
    HomeLoopWebViewController *vc=[[HomeLoopWebViewController alloc]init];
    vc.ctitle=@"澳际教育";
    vc.urlString=[loopArray[[tap view].tag] objectForKey:@"url"];
    [self.navigationController pushViewController:vc animated:YES];
    
    
}
-(void)tapTheCustomImage:(CustomImageView*)imgeview
{
    
    switch (imgeview.tag) {
        case 0:
        {
            ForeignStudyViewController *mainVC=[[ForeignStudyViewController alloc]init];
            self.loadtype=LoadTypeBack;
            [self.navigationController pushViewController:mainVC animated:YES];
            
            
        }
            break;
        case 1:{
            XHYWebViewController *mainVC=[[XHYWebViewController alloc]init];

            [self.navigationController pushViewController:mainVC animated:YES];
        }
        case 2:{//国际游学
            NationalStudyViewController *mainVC=[[NationalStudyViewController alloc]init];
            
            [self.navigationController pushViewController:mainVC animated:YES];
        }
            
            
            break;
        case 4:{
            
            AJMoreinfoViewController* moreinfo = [[AJMoreinfoViewController alloc] init];
            [self.navigationController pushViewController:moreinfo animated:YES];
        }
            break;
            
        case 5:{
            guessYouLikerController* guessyou = [[guessYouLikerController alloc] init];
            [self.navigationController pushViewController:guessyou animated:YES];
        }
            break;
        default:
            break;
    }
    NSLog(@"tag==%i",imgeview.tag);
    
}

-(void)getCountryList//国家列表
{
    [YHNetwork getInformationWithReguestType:RequestTypeGet WithParameters:nil WithApi:@"country" WhenSuccess:^(NSMutableDictionary *response) {
        [DataSingleTon shareDataSingleTon].countryList=response;
        
    } WhenFailure:^(NSError *failure) {
        
    }];
    
}
-(void)getCityList//城市列表
{

    [YHNetwork getInformationWithReguestType:RequestTypeGet WithParameters:nil WithApi:@"city" WhenSuccess:^(NSMutableDictionary *response) {
        [DataSingleTon shareDataSingleTon].cityList=response;
        
    } WhenFailure:^(NSError *failure) {
        
    }];
}

-(void)viewWillDisappear:(BOOL)animated
{


}

@end

